
<template>
  <div class="w1 h1 main_content">
    <div class="search-content">
      <!-- 搜索条 -->
      <Col class="panel search-panel"
        :span="24"
        style="padding:15px;box-sizing:border-box;">
      <Form inline
        :model="formHeader"
        :label-width="80">
        <FormItem label="企业名称："
          v-if="userRole!='ROLE_DEMO'">
          <Select v-model="formHeader.companyId"
            style="width:200px"
            @on-change="handlCompanyChange">
            <Option v-for="(item,index) in companyList"
              :value="item.id"
              :key="index"
              :label="item.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="企业名称："
          v-if="userRole=='ROLE_DEMO'">
          <Select v-model="formHeader.companyId"
            style="width:200px"
            @on-change="handlCompanyChange">
            <Option v-for="(item,index) in companyList"
              :value="item.id"
              :key="index"
              :label="!!item.alias?item.alias:item.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称："
          v-if="userRole!='ROLE_DEMO'">
          <Select clearable
            v-model="formHeader.deviceId"
            style="width:200px"
            @on-change="handlDeviceChange">
            <Option v-for="(item,index) in deviceList"
              :value="item.id"
              :key="index"
              :label="item.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称："
          v-if="userRole=='ROLE_DEMO'">
          <Select clearable
            v-model="formHeader.deviceId"
            style="width:200px"
            @on-change="handlDeviceChange">
            <Option v-for="(item,index) in deviceList"
              :value="item.id"
              :key="index"
              :label="!!item.alias?item.alias:item.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="参数名称：">
          <Select clearable
            v-model="formHeader.dataType"
            style="width:200px"
            @on-change="triggerAliasChange">
            <Option v-for="(item,index) in deviceAlias"
              :value="item.id"
              :key="index"
              :label="item.channelAlias"></Option>
          </Select>
        </FormItem>
        <FormItem label="查询时间：">
          <DatePicker :clearable="false"
            v-model="formHeader.timeRange"
            format="yyyy/MM/dd"
            type="daterange"
            :options="timeOptions"
            placement="right-start"
            placeholder="请选择日期"
            @on-change="handleDateChange"
            style="width:200px"></DatePicker>
        </FormItem>
        <FormItem class="margin-left-20">
          <Button type="primary"
            style="margin-right:15px;"
            @click="_requireThing">查询</Button>
          <Button type="primary"
            style="margin-right:15px;"
            @click="_exportFile">导出</Button>
          <Button v-if="showChartBtn"
            type="primary"
            @click.native="viewChart">查看曲线</Button>
        </FormItem>
      </Form>
      <span style="color:#c0c0c0;font-size:12px;">注：可查询三年的历史数据，仅显示三个月的参数数据曲线</span>
      </Col>
    </div>
    <div class="scroll__content history_content">
      <Row class="scroll-content__row">
        <!-- 表格 -->
        <Col class="panel table-panel"
          style="margin-bottom:10px;"
          :span="24">
        <Table id="out-table"
          ref="exportRef"
          :columns="userRole=='ROLE_DEMO'?columnsOfDemo:columns"
          :data="tableData"
          border
          fit
          :loading="pageInfo.loading"></Table>
        </Col>
        <!-- <Col span="24"
          style="text-align:center;margin-bottom:10px;"
          v-if="showMoreBtn">
        <Button @click="handleShowMoreData">查看更多</Button>
        </Col> -->
        <!-- 分页 -->
        <Col class="panel page-panel cf"
          :span="24">
        <div class='page-title'>
          <p>显示
            <span>{{startTime?moment(startTime).format('YYYY-MM-DD'):""}}</span>-
            <span>{{endTime?moment(endTime).format('YYYY-MM-DD'):""}}</span>数据，共<span>{{total}}</span>条
          </p>
        </div>
        <Page :total="pageInfo.total"
          show-total
          :current.sync="pageInfo.page"
          class="fr"
          @on-change="switchThePaging"
          :page-size="15"></Page>
        </Col>
        <Col span="24"
          class="page-bottom">
        </Col>
        <Modal footer-hide
          v-model="dialogVisable"
          width="70%">
          <div style="height: 400px;padding: 5px;">
            <hisChart :mapData="mapData"
              :currentName="currentName"
              v-if="dialogVisable"></hisChart>
          </div>
        </Modal>
      </Row>
    </div>
  </div>
</template>
<script>
import {
  getCompanyListOfSingle,
  getDeviceListOfNew,
  getDeviceAliasList,
  getHistoryList
} from '@/api'

import hisChart from '@/components/history/his-chart'

import ALIES_ARR from './alies'
import { mapState } from 'vuex'

let lasterPager = null
let skip = 0
let caiShuStartTime = 0
export default {
  components: {
    hisChart
  },
  computed: {
    ...mapState({
      userRole: state => state.userInfo.rname
    })
  },

  async mounted() {
    await this._getCompanyList()
    this._getHistoryList()
  },

  data() {
    return {
      dialogVisable: false,
      showChartBtn: false,
      timeOptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now()
        }
      },
      mapData: {},
      formHeader: {
        companyId: '',
        deviceId: '',
        dataType: '',
        status: '',
        timeRange: [
          this.moment()
            .add(-7, 'days')
            .format(),
          this.moment()
            .add(-1, 'days')
            .format()
        ]
      },
      pageInfo: {
        page: 1,
        total: 0,
        loading: false
      },
      columnsOfDemo: [
        {
          title: '序号',
          key: 'index',
          type: 'index',
          align: 'center'
        },
        {
          title: '企业名称',
          key: 'companyAlias',
          align: 'center'
        },
        {
          title: '区域',
          key: 'groupName',
          align: 'center'
        },
        {
          title: '设备名称',
          key: 'deviceAlias',
          align: 'center'
        },
        {
          title: '参数名称',
          key: 'des',
          align: 'center'
        },
        {
          title: '参数值',
          align: 'center',
          key: 'type',
          render: (h, params) => {
            const type = params.row.type,
              value = params.row.value,
              unit = params.row.unit
            if (type >= 53 && type <= 55 && value == 0) {
              return h('span', '-')
            } else {
              return h('span', value + unit)
            }
          }
        },
        {
          title: '采集时间',
          align: 'center',
          key: 'createdAt',
          render: (h, params) => {
            let time = params.row.createdAt
            return h('span', this.filterTime(time))
          }
        }
      ],
      columns: [
        {
          title: '序号',
          key: 'index',
          type: 'index',
          align: 'center'
        },
        {
          title: '企业名称',
          key: 'companyName',
          align: 'center'
        },
        {
          title: '区域',
          key: 'groupName',
          align: 'center'
        },
        {
          title: '设备名称',
          key: 'deviceName',
          align: 'center'
        },
        {
          title: '参数名称',
          key: 'des',
          align: 'center'
        },
        {
          title: '参数值',
          align: 'center',
          key: 'type',
          render: (h, params) => {
            const type = params.row.type,
              value = params.row.value,
              unit = params.row.unit
            if (type >= 53 && type <= 55 && value == 0) {
              return h('span', '-')
            } else {
              return h('span', value + unit)
            }
          }
        },
        {
          title: '采集时间',
          align: 'center',
          key: 'createdAt',
          render: (h, params) => {
            let time = params.row.createdAt
            return h('span', this.filterTime(time))
          }
        }
      ],
      tableData: [],
      companyList: [],
      deviceList: [],
      deviceAlias: [],
      selectDeviceId: '',
      currentName: '',
      showMoreBtn: false,
      //
      total: 0,
      currentTotal: 0,
      startTime: null,
      endTime: null,
      firstTableData: [],

      // 上一次的总页数
      lastTotalPage: 0,
      isMore: false,
      isUsePageChange: false,
      aliasCanShowBtn: false,
      dateCanShowBtn: true
    }
  },

  methods: {
    // 格式化时间
    filterTime(time) {
      return this.moment(time).format('YYYY-MM-DD HH:mm:ss')
    },

    triggerAliasChange(value) {
      const vm = this
      if (value && value !== 0) {
        vm.currentName = vm.deviceAlias.find(t => t.id === value).channelAlias
        if (vm.selectDeviceId.startsWith('9')) {
          vm.aliasCanShowBtn = true
        } else {
          if (vm.formHeader.deviceId) {
            if (vm.formHeader.dataType >= 5 && vm.formHeader.dataType <= 15) {
              vm.aliasCanShowBtn = true
            } else if (vm.formHeader.dataType === 63) {
              vm.aliasCanShowBtn = true
            } else {
              vm.aliasCanShowBtn = false
            }
          } else {
            vm.aliasCanShowBtn = false
          }
        }
      } else {
        vm.aliasCanShowBtn = false
      }

      if (vm.dateCanShowBtn && vm.aliasCanShowBtn) {
        vm.showChartBtn = true
      } else {
        vm.showChartBtn = false
      }
    },

    // 导出文件
    _exportFile() {
      let vm = this
      let startTime = vm.moment(vm.formHeader.timeRange[0]).format('YYYY/MM/DD')
      let endTme = vm.moment(vm.formHeader.timeRange[1]).format('YYYY/MM/DD')
      vm.$nextTick(() => {
        vm.$refs.exportRef.exportCsv({
          filename: `${startTime}-${endTme}.csv`,
          data: [...this.tableData].map((k, i) => {
            k.createdAt = this.moment(k.createdAt).format('YYYY-MM-DD HH:mm:ss')
            k['index'] = i + 1
            if (k.type >= 53 && k.type <= 55 && k.value == 0) {
              k.type = '-'
            } else {
              k.type = k.value + k.unit
            }
            return k
          })
        })
        this._getHistoryList()
      })
    },

    // 查看曲线
    viewChart() {
      const _t = this
      _t.dialogVisable = true
      let time = [..._t.formHeader.timeRange]
      let timeRangeStart = _t.moment(time[0]).valueOf(),
        timeRangeEnd = _t.moment(time[1]).valueOf() + 86399999

      let params = {
        deviceId: _t.formHeader.deviceId,
        // type: "5,6,7,8,9,10,11,12,13,14,15",
        dataType: _t.formHeader.dataType,
        timeRangeStart,
        timeRangeEnd
      }
      this.mapData = params
    },

    // 分页
    switchThePaging(index) {
      this.pageInfo.page = index
      if (this.showMoreBtn) {
        this.showMoreBtn = false
      }
      this.isUsePageChange = true
      this._getHistoryList()
    },

    // 企业变化
    handlCompanyChange(id) {
      this.formHeader.deviceId = ''
      this.formHeader.dataType = ''
      this.deviceList = []
      this.deviceAlias = []
      if (!!id) {
        this.formHeader.companyId = id
        this._getDeviceList()
      } else {
        this.showChartBtn = false
      }
    },

    // 设备更改
    handlDeviceChange(id) {
      this.formHeader.dataType = ''
      this.deviceAlias = []
      if (!!id) {
        this.formHeader.deviceId = id
        this._getDeviceAliasList()
      } else {
        this.showChartBtn = false
      }
    },

    // 获取设备参数列表
    _getDeviceAliasList() {
      let _t = this
      let value = _t.formHeader.deviceId || ''
      let selectedDeviceId = _t.deviceList.find(t => t.id === value).deviceId
      this.selectDeviceId = selectedDeviceId
      if (selectedDeviceId.startsWith('9')) {
        let params = {
          deviceId: selectedDeviceId
        }
        getDeviceAliasList(params).then(res => {
          if (res.code == 200) {
            this.deviceAlias = [...res.data]
          } else {
            this.deviceAlias = []
          }
        })
      } else {
        this.deviceAlias = [...ALIES_ARR]
      }
    },

    // 查询事件
    _requireThing() {
      const vm = this
      vm.pageInfo.page = 1
      vm.lastTotalPage = 0
      vm.showMoreBtn = false
      vm.isMore = false
      skip = 0
      vm._getHistoryList()
    },

    // 获取企业列表
    _getCompanyList() {
      const params = { cityId: '' }
      return new Promise((reolve, reject) => {
        getCompanyListOfSingle(params).then(res => {
          if (res.code == 200) {
            this.companyList = res.data
            this.formHeader.companyId = res.data[0].id
            this._getDeviceList()
            reolve()
          }
        })
      })
    },

    _getDeviceList() {
      const vm = this
      const companyId = vm.formHeader.companyId
      const params = { companyId, size: 1000 }
      getDeviceListOfNew(params).then(res => {
        if (res.code === 200) {
          vm.deviceList = res.data.list
        } else {
          vm.deviceList = []
        }
      })
    },

    // 获取历史数据
    _getHistoryList() {
      const vm = this
      vm.pageInfo.loading = true
      const time = vm.formHeader.timeRange
      let timeRangeStart = vm.moment(time[0]).valueOf()
      let timeRangeEnd = vm.moment(time[1]).valueOf()
      if (timeRangeStart === timeRangeEnd) {
        let today = vm
          .moment(new Date(new Date().setHours(0, 0, 0, 0)))
          .valueOf()
        if (timeRangeStart === today) {
          timeRangeEnd = vm.moment().valueOf()
        } else {
          timeRangeEnd = timeRangeStart + 86399999
        }
      } else {
        timeRangeEnd = timeRangeEnd + 86399999
      }

      const params = {
        page: vm.pageInfo.page,
        size: 15,
        companyId: vm.formHeader.companyId,
        // companyId: '1a11d5f1-6332-4773-978c-5a76670c586d',
        deviceId: vm.formHeader.deviceId,
        // deviceId: 'f9d7cd57-492c-47a2-8c08-59866b22e253',
        type: vm.formHeader.dataType,
        timeRangeStart,
        timeRangeEnd
      }
      // const skip = vm.pageInfo.page - 1
      // vm.isMore && skip && (params['skip'] = skip)
      getHistoryList(params).then(res => {
        if (res.code === 200 && res.data) {
          // 当访问到的是最后一页
          // if (lasterPager && vm.pageInfo.page === lasterPager) {
          //   vm.showMoreBtn = true
          //   caiShuStartTime = res.data.timeRange[0]
          //   console.log('当前访问最后一页', lasterPager)
          //   if (
          //     caiShuStartTime < timeRangeStart ||
          //     timeRangeEnd === timeRangeStart
          //   ) {
          //     vm.showMoreBtn = false
          //     vm.isMore = false
          //   }
          // } else {
          //   vm.showMoreBtn = false
          // }

          // // 如果是分页切换需要将page
          // if (!vm.isUsePageChange) {
          //   vm.pageInfo.total = lastPageTotal
          //     ? lastPageTotal + res.data.total
          //     : res.data.total
          //   vm.total = lastPageTotal
          //     ? lastPageTotal + res.data.total
          //     : res.data.total
          //   lasterPager = Math.ceil(vm.total / 15)
          // }
          vm.total = res.data.total
          vm.startTime = res.data.timeRange[0]
          vm.endTime = res.data.timeRange[1]
          vm.pageInfo.total = res.data.total
          vm.tableData = res.data.data
        } else {
          vm.pageInfo.total = 0
          vm.tableData = []
        }
        vm.pageInfo.loading = false
      })
    },

    // 时间选择器chagne
    handleDateChange() {
      const vm = this
      const timeRange = vm.formHeader.timeRange
      if (Array.isArray(timeRange) && timeRange.length === 2) {
        const start = vm.moment(timeRange[0])
        const end = vm.moment(timeRange[1])
        const diff = end.diff(start, 'month')
        if (diff > 2) {
          vm.dateCanShowBtn = false
        } else {
          vm.dateCanShowBtn = true
        }
      }
      if (vm.dateCanShowBtn && vm.aliasCanShowBtn) {
        vm.showChartBtn = true
      } else {
        vm.showChartBtn = false
      }
    },

    handleShowMoreData() {
      const vm = this
      skip = vm.pageInfo.page
      const total = vm.pageInfo.total
      vm.pageInfo.total = vm.pageInfo.total + 15
      vm.pageInfo.page = vm.pageInfo.page + 1
      vm.isMore = true
      vm.isUsePageChange = false
      this._getHistoryList(1, total)
    }
  }
}
</script>